package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.model.account.UserAccount;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;

@Component
public class AccountReceiver {
    @Autowired
    private UserAccountService userAccountService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConst.QUEUE_USER_REGISTER, durable = "true",autoDelete = "false"),
            exchange = @Exchange(name = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ) )
    public void regist(Long userId, Message message, Channel channel) {
        try {
            if (userId!=null){
                UserAccount userAccount = new UserAccount();
                userAccount.setUserId(userId);
                userAccount.setTotalAmount(new BigDecimal("100"));
                userAccount.setAvailableAmount(new BigDecimal("100"));
                userAccountService.save(userAccount);
            }
        } catch (Exception e) {
            try {
                channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            System.out.println(e.getMessage());
        }
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
